package com.ttc.mBackup.BackupImages;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;


import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;

import android.view.KeyEvent;
import android.view.View;

import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import android.widget.TextView;


import com.ttc.mBackup.R;

public class BackupInfoActivity extends Activity {

	private Button btnSource;
	private Button btnFileName;
	private Button btnDescription;
	private Button btnOK;
	private Button btnCancel;
	

	private ZipFileProcess zipTask;

	private String backupSource = "Backup from: ";
	private String backupFileName;
	private String descriptions;
	private int sourceType = 0;

	
	@Override
	protected void onResume() {
		if(zipTask == null)Log.i("mediastore", "ziptask is null");
		super.onResume();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		((CustomApplication) getApplication()).attach(this);
		super.onRestoreInstanceState(savedInstanceState);
		
		
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		((CustomApplication) getApplication()).detach(this);
		super.onSaveInstanceState(outState);
		
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.i_layout_backup_info);

		descriptions = "NO DESCRIPTION";
		btnOK = (Button) findViewById(R.id.i_layout_backup_info_btnOK);
		btnCancel = (Button) findViewById(R.id.i_layout_backup_info_btnCancel);
		btnSource = (Button) findViewById(R.id.i_layout_backup_info_btnSource);
		btnFileName = (Button) findViewById(R.id.i_layout_backup_info_btnFileName);
		btnDescription = (Button) findViewById(R.id.i_layout_backup_info_btnDescription);

		btnOK.setOnClickListener(oclRunBackup);
		btnCancel.setOnClickListener(oclCancel);
		btnSource.setOnClickListener(oclSource);
		btnFileName.setOnClickListener(oclFileName);
		btnDescription.setOnClickListener(oclDescription);

		backupFileName = createBackupFileName();

		btnFileName.setText(backupFileName);
		
		if(zipTask == null) ShowBackupSourceDialog();
	}

	private OnClickListener oclRunBackup = new OnClickListener() {

		@Override
		public void onClick(View v) {
			runBackup();
		}
	};

	private void runBackup() {

		String date = getCurrentDate();
		String description = descriptions;
		StringBuilder sb = new StringBuilder(date);
		sb.append(System.getProperty("line.separator"));
		sb.append(description);
		backupImages(backupFileName, sb.toString(), sourceType);
	}

	@Override
	protected void onDestroy() {

		if (zipTask != null && !zipTask.isFinished) {
			// delete files
			FileManager.deleteFile(zipTask.getZipFile());
			FileManager.deleteInfoFile();
		}

		super.onDestroy();
	}

	private OnClickListener oclCancel = new OnClickListener() {

		@Override
		public void onClick(View v) {
			BackupInfoActivity.this.finish();

		}
	};

	private OnClickListener oclSource = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ShowBackupSourceDialog();
		}
	};

	private OnClickListener oclFileName = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ShowFileNameDialog();

		}
	};

	private OnClickListener oclDescription = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ShowDescriptionsDialog();
		}
	};

	@Override
	public void onBackPressed() {

		if (zipTask != null && !zipTask.isFinished) {
			new AlertDialog.Builder(BackupInfoActivity.this).setIcon(
					android.R.drawable.ic_dialog_alert).setTitle(
					"Running backup images").setMessage(
					"Backup images is running, are you sure to cancel?")
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									cancelBackup();
								}

							}).setNegativeButton("No", null).show();
		} else
			super.onBackPressed();
	}

	private void backupImages(String fileName, String descriptions,
			int source_type) {

		fileName += ".zip";
		// create backup info file
		String fileInfo = FileManager.CreateInfoFile(descriptions);

		// get all image paths
		ArrayList<String> imagePaths = ImageManager.getActualImagePath(this,
				source_type);
		imagePaths.add(fileInfo);

//		long fileSIze  = FileManager.getFileSize(imagePaths);
//		double free = FileManager.getFreeSpaceOnSDCard();
//		
//		Log.i("mediastore", "SIZE: " + fileSIze + "  FREE: " + free);
		
		if (!FileManager.checkEnoughMemory(imagePaths))
			Toast.makeText(getApplicationContext(),
					"Not enough free space on SD Card", Toast.LENGTH_LONG)
					.show();
		else {
			// run zip file asynctask
			zipTask = new ZipFileProcess(BackupInfoActivity.this, imagePaths, fileName);
			// zipTask.cancel(false);
			zipTask.execute();
		}
	}

	private String createBackupFileName() {
		String fileName = "mBackup_";
		fileName += getCurrentDate(); // .jmb: json mBackup
		return fileName;
	}

	private String getCurrentDate() {
		// create backup file name
		Date d = new Date();
		String s = DateFormat.format("ddMMyyyy_hhmmss ", d.getTime())
				.toString();
		return s;
	}

	private void cancelBackup() {
		// delete zip file
		FileManager.deleteFile(zipTask.getZipFile());
		FileManager.deleteInfoFile();
		BackupInfoActivity.this.finish();
	}

	public void ShowFileNameDialog() {

		final Dialog dialog = new Dialog(this, R.style.WideDialogTheme);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.i_custom_dialog);
		dialog.setTitle("Enter backup name");

		final EditText txtContent = (EditText) dialog
				.findViewById(R.id.i_custom_dialog_txtContent);
		txtContent.setText(backupFileName);
		Button btnOk = (Button) dialog.findViewById(R.id.i_custom_dialog_btnOK);
		Button btnCancel = (Button) dialog
				.findViewById(R.id.i_custom_dialog_btnCancel);

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.cancel();

			}
		});

		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				backupFileName = txtContent.getText().toString();
				btnFileName.setText("Backup name: " + backupFileName);

				dialog.cancel();
			}
		});

		OnKeyListener onEnter = new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					backupFileName = txtContent.getText().toString();
					btnFileName.setText("Backup name: " + backupFileName);

					dialog.cancel();
				}
				return false;
			}
		};

		txtContent.setOnKeyListener(onEnter);
		dialog.show();

	}

	public void ShowDescriptionsDialog() {

		final Dialog dialog = new Dialog(this, R.style.WideDialogTheme);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.i_custom_dialog);
		dialog.setTitle("Enter descriptions");

		final EditText txtContent = (EditText) dialog
				.findViewById(R.id.i_custom_dialog_txtContent);
		txtContent.setText(backupFileName);
		Button btnOk = (Button) dialog.findViewById(R.id.i_custom_dialog_btnOK);
		Button btnCancel = (Button) dialog
				.findViewById(R.id.i_custom_dialog_btnCancel);

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				dialog.cancel();

			}
		});

		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				descriptions = txtContent.getText().toString();
				btnDescription.setText("Descriptions: " + descriptions);
				dialog.cancel();
			}
		});

		OnKeyListener onEnter = new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {

					descriptions = txtContent.getText().toString();
					btnDescription.setText("Descriptions: " + descriptions);
					dialog.cancel();
				}
				return false;
			}
		};

		txtContent.setOnKeyListener(onEnter);
		dialog.show();

	}

	public void ShowBackupSourceDialog() {
		final CharSequence[] sources = new CharSequence[] { "SD Card", "Phone",
				"All" };

		AlertDialog.Builder builder = new AlertDialog.Builder(
				BackupInfoActivity.this);
		builder.setTitle("Select image source");

		// NategativeButton is on the right, so should be "Next"
		builder.setNegativeButton("Next",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ShowFileNameDialog();
					}

				});

		builder.setPositiveButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

		builder.setSingleChoiceItems(sources, 0,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
						case 0:
							sourceType = ImageManager.SDCARD;
							backupSource = "Backup from: " + sources[item];
							break;
						case 1:
							sourceType = ImageManager.PHONE;
							backupSource = "Backup from: " + sources[item];
							break;
						case 2:
							sourceType = ImageManager.ALL;
							backupSource = "Backup from: " + sources[item];
							break;
						default:
							break;
						}
						btnSource.setText(backupSource);
					}
				}).show();
	}
}
